const Joi = require("joi");
const md5 = require("md5");

module.exports = class extends doodoo.Controller {
    async _initialize() {}

    /**
     *
     * @api {post} /admin/public/login 客户登录
     * @apiDescription 客户登录授权
     * @apiGroup Admin
     * @apiVersion 0.0.1
     *
     * @apiParam {nickname} nickname 用户名
     * @apiParam {String} password 客户密码
     *
     * @apiSuccess {String} token jwt加密码
     * @apiSuccess {Json} admin 用户信息
     *
     * @apiSampleRequest /admin/public/login
     *
     */
    async login() {
        await this.validate(this.post, {
            nickname: Joi.string().required(),
            password: Joi.string().required()
        });

        const { nickname, password } = this.post;
        const ip = this.get("X-Real-IP") || this.ip;

        const admin = await this.model("admin")
            .query({
                where: {
                    nickname: nickname,
                    password: md5(password)
                }
            })
            .fetch();
        if (!admin) {
            this.fail("账号密码有误");
            return;
        }
        // 记录登录IP
        await this.model("admin_log")
            .forge({
                admin_id: admin.id,
                ip: ip,
                info: "登录"
            })
            .save();
        const token = this.jwtSign(admin, "", "786699892");
        this.success({ token, admin });
    }
};
